﻿using LoginDemo.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace LoginDemo.Controllers
{
    
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

      

        public UserViewModel CurrentLoginUser
        {
            get
            {
                var principal = HttpContext.User;
                if (principal != null)
                {
                    return new UserViewModel()
                    {
                        UserName = principal.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value,
                        Mobile = principal.Claims.FirstOrDefault(x => x.Type == ClaimTypes.MobilePhone)?.Value,
                        Id = int.Parse(principal.Claims.FirstOrDefault(x => x.Type == "Id")?.Value)
                    };
                }
                return null;
            }

        }

        public IActionResult Index()
        {
            ViewBag.Info = CurrentLoginUser.UserName;
            return View();
        }

        public IActionResult Index2()
        {

            return Content("ddddddddddddddddddddd");
        }


        public async Task<IActionResult> UserLogin()
        {
            //登录逻辑
            // var model = userService.UserLogin(input);

            //1.创建cookie 保存用户信息，使用claim。将序列化用户信息并将其存储在cookie中
            var claims = new List<Claim>()
            {
                new Claim(ClaimTypes.MobilePhone,"1500001000"),
                new Claim(ClaimTypes.Name,"userName"),
                new Claim("Id","10")
            };
            //2.创建声明主题 指定认证方式 这里使用cookie
            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            //3.配置认证属性 比如过期时间，是否持久化。。。。
            var authProperties = new AuthenticationProperties
            {
                //AllowRefresh = <bool>,
                // Refreshing the authentication session should be allowed.

                //ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),
               
                //IsPersistent = true,
                //持久化 ，比如 登录的时候 勾选记住我 复选框



            };
            //HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);  退出
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);
            return Content("Ok");

        }
    }
}
